package com.burst.reptile.modular.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.burst.reptile.common.constant.UserConstants;
import com.burst.reptile.common.utils.SecurityUtils;
import com.burst.reptile.common.utils.ServletUtils;
import com.burst.reptile.framework.aspectj.lang.annotation.Log;
import com.burst.reptile.framework.aspectj.lang.enums.BusinessType;
import com.burst.reptile.framework.security.LoginUser;
import com.burst.reptile.framework.security.service.TokenService;
import com.burst.reptile.framework.web.result.Result;
import com.burst.reptile.modular.system.entity.SysMenu;
import com.burst.reptile.modular.system.service.ISysMenuService;

import lombok.RequiredArgsConstructor;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author wujin
 * @since 2020-05-22
 */
@RestController
@RequestMapping("/system/menu")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysMenuController {

	private final ISysMenuService menuService;

	private final TokenService tokenService;

	/**
	 * 获取菜单列表
	 */
	@PreAuthorize("@ss.hasPermi('system:menu:list')")
	@GetMapping("/list")
	public Result<Object> list(SysMenu menu) {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		Long userId = loginUser.getUser().getUserId();
		List<SysMenu> menus = menuService.selectMenuList(menu, userId);
		return Result.success(menus);
	}

	/**
	 * 新增菜单
	 */
	@PreAuthorize("@ss.hasPermi('system:menu:add')")
	@Log(title = "菜单管理", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	public Result<Object> add(@Validated @RequestBody SysMenu menu) {
		if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
			return Result.error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
		}
		menu.setCreateUser(SecurityUtils.getUsername());
		return Result.success(menuService.insertMenu(menu));
	}

	/**
	 * 修改菜单
	 */
	@PreAuthorize("@ss.hasPermi('system:menu:edit')")
	@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
	@PutMapping("/edit")
	public Result<Object> edit(@Validated @RequestBody SysMenu menu) {
		if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
			return Result.error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
		}
		menu.setUpdateUser(SecurityUtils.getUsername());
		return Result.success(menuService.updateMenu(menu));
	}

	/**
	 * 删除菜单
	 */
	@PreAuthorize("@ss.hasPermi('system:menu:remove')")
	@Log(title = "菜单管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/remove/{menuId}")
	public Result<Object> remove(@PathVariable("menuId") Long menuId) {
		if (menuService.hasChildByMenuId(menuId)) {
			return Result.error("存在子菜单,不允许删除");
		}
		if (menuService.checkMenuExistRole(menuId)) {
			return Result.error("菜单已分配,不允许删除");
		}
		return Result.success(menuService.deleteMenuById(menuId));
	}

	/**
	 * 获取菜单下拉树列表
	 */
	@GetMapping("/treeselect")
	public Result<Object> treeselect(SysMenu menu) {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		Long userId = loginUser.getUser().getUserId();
		List<SysMenu> menus = menuService.selectMenuList(menu, userId);
		return Result.success(menuService.buildMenuTreeSelect(menus));
	}

	/**
	 * 加载对应角色菜单列表树
	 */
	@GetMapping("/roleMenuTreeselect/{roleId}")
	public Result<Object> roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		List<SysMenu> menus = menuService.selectMenuList(new SysMenu(), loginUser.getUser().getUserId());
		Map<String, Object> map = new HashMap<>();
		map.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
		map.put("menus", menuService.buildMenuTreeSelect(menus));
		return Result.success(map);
	}

}
